package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;


    //分页查询文章列表
    @Override
    public ResponseResult findAllList(WmNewsPageReqDto dto) {

//        检验参数
        dto.checkParam();

        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();

//        判断查询条件是否为空
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        wrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());

//        进行时间排序
        wrapper.orderByDesc(WmNews::getCreatedTime);

        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        Page<WmNews> wmNewsPage = baseMapper.selectPage(page, wrapper);

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) wmNewsPage.getTotal());

        responseResult.setData(wmNewsPage.getRecords());

        return responseResult;
    }


    //    发布文章或者修改文章
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {

//        文章的文本字段不能为空
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        提交参数
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        if (dto.getImages() != null || dto.getImages().size() > 0) {
            List<String> images = dto.getImages();
//            将集合图片转化为字符串
            String imagesStr = StringUtils.join(images, ",");
            wmNews.setImages(imagesStr);

            //如果当前封面类型为自动 -1
            if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
                wmNews.setType(null);
            }
//        判断是更新还是发布文章
            saveOrUpdateNews(wmNews);

//            判断是否是保存为草稿文件
            if (wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }

//            不是草稿文件，保存对应的关联表信息
//            提取发布内容的图片信息
            List<String> imageUrls = getImgesUrls(wmNews.getContent());

//            保存文章内容图片和素材的关系
            saveReleateMeter(imageUrls, wmNews.getId());

//            保存文章封面图片与素材的关系,如果封面条件为自动获取需要自动判断
            saveRelativeInfoForCover(dto, wmNews, imageUrls);

//            审核文章
//            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
//            定时任务添加
            wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }


    //            保存文章封面图片与素材的关系,如果封面条件为自动获取需要自动判断
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> imageUrls) {

        List<String> images = dto.getImages();

//        判断是否为自动获取封面
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (dto.getImages().size() > 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
//            取前三张作为封面
                images = imageUrls.stream().limit(3).collect(Collectors.toList());
            } else if (imageUrls.size() >= 1 && imageUrls.size() < 3) {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = imageUrls.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //修改文章
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }
//        保存文章封面图片与关系表中的关系
        if (images != null && images.size() > 0) {
            saveWithMeterOr(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }


    //            保存文章内容图片和素材的关系
    private void saveReleateMeter(List<String> imageUrls, Integer newId) {
//        抽取一个公共的方法用户保存文章图片或者文章内容图片的关系,0代表文章内容关系，1代表文章封面关系
        saveWithMeterOr(imageUrls, newId, WemediaConstants.CANCEL_COLLECT_MATERIAL);
    }

    //        抽取一个公共的方法用户保存文章图片或者文章内容图片的关系,0代表文章内容关系，1代表文章封面关系
    private void saveWithMeterOr(List<String> imageUrls, Integer newId, Short type) {
//        判断图片是否存在
        if (imageUrls != null && imageUrls.size() != 0) {
//        获取图片信息id从wm_material表中
            QueryWrapper<WmMaterial> wrapper = new QueryWrapper<>();
            wrapper.in("url", imageUrls);
//        查询所有图片地址信息id
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(wrapper);


//        提取图片的id
            List<Integer> imageIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            if (imageIds.size() == 0 || imageIds == null) {
                throw new CustomException(AppHttpCodeEnum.METERIASL_REFERENCE_FAIL);
            }
            if (imageIds.size() != imageUrls.size()) {
                throw new CustomException(AppHttpCodeEnum.METERIASL_REFERENCE_FAIL);
            }

            //        设置关连的信息表
            wmNewsMaterialMapper.saveRelations(imageIds, newId, type);

        }
    }

    //    发布文章或者修改文章
    private void saveOrUpdateNews(WmNews wmNews) {
//        填充缺少字段
        wmNews.setEnable((short) 1);//默认1上架
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());

//        根据id判断
        if (wmNews.getId() == null) {
//        发布文章
            int insert = baseMapper.insert(wmNews);
        } else {
//            修改文章
//            删除关联的表
            QueryWrapper<WmNewsMaterial> wrapper = new QueryWrapper<>();
            wrapper.eq("material_id", wmNews.getId());
            wmNewsMaterialMapper.delete(wrapper);
            baseMapper.updateById(wmNews);
        }

    }

    //            提取发布内容的图片信息
    private List<String> getImgesUrls(String content) {

        List<String> imgUrls = new ArrayList<>();

//        获取content容
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
//                获取图片信息
                String imageUrl = (String) map.get("value");
//                存入集合中
                imgUrls.add(imageUrl);
            }

        }
        return imgUrls;
    }


    /**
     * 自媒体文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

//        查询文章
        WmNews wmNews = baseMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "没有文章");
        }


        //3.判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }

//        修改文章上下架状态
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            wmNews.setEnable(dto.getEnable());
            updateById(wmNews);
        }


        //         发送消息，通知article端修改文章配置
        if (wmNews.getId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());
//            第一个参数topic，第二个数据
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }


    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.结果返回
        return ResponseResult.okResult(wmNews);
    }


    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.参数检查
        dto.checkParam();

        //记录当前页
        int currentPage = dto.getPage();

        //2.分页查询+count查询
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(currentPage, dto.getSize(), count);
        responseResult.setData(wmNewsVoList);
        return responseResult;
    }


    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.查询用户信息
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());

        //4.封装vo返回
        WmNewsVo vo = new WmNewsVo();
        //属性拷贝
        BeanUtils.copyProperties(wmNews, vo);
        if (wmUser != null) {
            vo.setAuthorName(wmUser.getName());
        }

        ResponseResult responseResult = new ResponseResult().ok(vo);

        return responseResult;
    }

    /**
     * 文章审核，修改状态
     *
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.修改文章的状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //审核成功，则需要创建app端文章数据，并修改自媒体文章
        if (status.equals(WemediaConstants.WM_NEWS_AUTH_PASS)) {
            //创建app端文章数据
            ResponseResult responseResult = wmNewsAutoScanService.saveAppArticle(wmNews);
            if (responseResult.getCode().equals(200)) {
                wmNews.setArticleId((Long) responseResult.getData());
                wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
                updateById(wmNews);
            }
        }

        //4.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
